package com.mmg.spzx.product.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.mmg.spzx.model.entity.product.Category;
import com.mmg.spzx.product.mapper.CategoryMapper;
import com.mmg.spzx.product.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Service
public class CategoryServiceImpl implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @Override
    public List<Category> findByParentId() {
        //1.先从redis中查询
        String categoryListJson = redisTemplate.opsForValue().get("category:one");
        //2.判断是否为空
        if (StringUtils.hasText(categoryListJson)) {
            //3.如果不为空，直接返回
            return JSONObject.parseArray(categoryListJson, Category.class);
        }
        //4.如果为空，从数据库中查询
        List<Category> categoryList = categoryMapper.findByParentId();
        //5.将查询结果存入redis中
        redisTemplate.opsForValue().set("category:one", JSONObject.toJSONString(categoryList), 1, TimeUnit.DAYS);
        return categoryList;
    }

    @Override
    public List<Category> findCategoryTree() {
        //1.查询所有分类
        List<Category> categoryList = categoryMapper.findAll();
        //2.遍历过滤出所有一级分类
        List<Category> oneCategoryList = categoryList.stream().filter(item -> item.getParentId().longValue() == 0).collect(Collectors.toList());
        if (!CollectionUtils.isEmpty(oneCategoryList)) {
            oneCategoryList.forEach(oneCategory -> {
                //3.遍历过滤出所有二级分类
                List<Category> twoCategoryList = categoryList.stream().filter(item -> item.getParentId().longValue() == oneCategory.getId().longValue()).collect(Collectors.toList());
                //将二级分类设置到一级分类中
                oneCategory.setChildren(twoCategoryList);
                if (!CollectionUtils.isEmpty(twoCategoryList)) {
                    //4.遍历过滤出所有三级分类
                    twoCategoryList.forEach(twoCategory -> {
                        List<Category> threeCategoryList = categoryList.stream().filter(item -> item.getParentId().longValue() == twoCategory.getId().longValue()).collect(Collectors.toList());
                        //将三级分类设置到二级分类中
                        twoCategory.setChildren(threeCategoryList);
                    });
                }
            });
        }
        return oneCategoryList;
    }
}
